package com.wangyf.thread.c_017_readwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁学习
 * ReentrantReadWriteLock可以得到两把锁，读锁和写锁
 * 读的时候可以多线程同时读，写的时候同时只能一个线程进行修改，读的时候不能进行写，写的时候不能进行读
 * 也就是读写锁，读读不互斥，读写互斥，写写互斥。
 * 这里面的读锁：
 * @author wangyf
 * @date 2021/1/7 9:17
 */
public class ReadWriteLockTest {
    private static ReentrantLock lock = new ReentrantLock();
    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();

    static int count = 0;

    void read(Lock lock) {
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(1);
            System.out.println("read end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void write(Lock lock, int count) {
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(1);
            ReadWriteLockTest.count = count;
            System.out.println("write end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockTest t = new ReadWriteLockTest();
//        Runnable readRu = () -> t.read(lock);
//        Runnable writeRu = () -> t.write(lock, 10);
        Runnable readRu = () -> t.read(readLock);
        Runnable writeRu = () -> t.write(writeLock, 10);
        for (int i = 0; i < 5; i++) new Thread(readRu).start();
        for (int i = 0; i < 2; i++) new Thread(writeRu).start();
    }
}
